<template>
  <div>
    <a-row class="h80 lh80">
      <a-col :span="8">
        <a-button class="mr12" type="primary" @click="showDrawer"> 添加子部门</a-button>
        <a-button :disabled="!selectedRowKeys.length" @click="del"> 批量删除</a-button>
      </a-col>
      <a-col :span="4" :offset="12">
        <a-input-search placeholder="搜索" @search="onSearch" />
      </a-col>
    </a-row>
    <a-table
      :columns="table"
      :data-source="data"
      row-key="id"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange
      }"
      :pagination="pagination"
      @change="tableChange"
      align="center"
    >
      <span slot="action" slot-scope="text, record">
        <a-tag @click="edit(record)">编辑</a-tag>
      </span>
    </a-table>
    <a-drawer :title="title" :width="540" :visible="visible" :wrap-style="{ overflow: 'auto' }" @close="onClose">
      <a-form :form="form" layout="vertical" style="height: 630px; width: 470px" @submit="handleSubmit">
        <a-form-item label="部门名称">
          <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入' }] }]" />
        </a-form-item>
        <a-form-item label="部门说明">
          <a-input v-decorator="['desc', { initialValue: perArchitecture.desc }]" type="textarea" />
        </a-form-item>
        <div
          :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
            zIndex: 1
          }"
        >
          <a-button :style="{ marginRight: '12px' }" @click="onClose"> 取消 </a-button>
          <a-button type="primary" html-type="submit">确定</a-button>
        </div>
      </a-form>
    </a-drawer>
  </div>
</template>
<script>
import { getProvince, getArea } from "@/api/area";
import { addDepartment, delDepartments, putDepartment, getDepManageByDepId } from "@/api/department/department";
import { listAll } from "@/api/staff/staff";
import { mapState } from "vuex";
const table = [
  {
    title: "部门名称",
    dataIndex: "name"
  },
  {
    title: "人数",
    dataIndex: "empDirectCount"
  },
  {
    title: "子部门",
    dataIndex: "childCount"
  },
  {
    title: "操作",
    dataIndex: "action",
    scopedSlots: { customRender: "action" }
  }
];

export default {
  props: ["selectedId", "level", "isCompany", "getTree"],
  inject: ["reload"],
  data() {
    return {
      form: this.$form.createForm(this),
      title: "添加部门",
      visible: false,
      province: [],
      area: [],
      values: [],
      allEmpInfo: [],
      table,
      data: [],
      selectedRowKeys: [],

      expandedKeys: [],
      searchValue: "",
      autoExpandParent: true,
      treeData: [],
      replaceFields: {
        title: "name"
      },
      dataList: [],
      architecture: [],
      depProps: { label: "name", children: "depChildList" },
      posProps: { label: "name", children: "positionChildList" },
      architectureDialogVisible: false,
      architectureForm: this.$form.createForm(this),
      perArchitecture: { type: 1 },
      operateArchitecture: { method: "", title: "" },
      depType: [
        { label: "部门", value: 1 },
        { label: "事业群", value: 2 },
        { label: "组", value: 3 },
        { label: "中心", value: 4 },
        { label: "子公司", value: 5 },
        { label: "事业部", value: 6 }
      ],
      empInfoList: [],

      empInfoDialog: { visible: false, title: "" },
      nameOrPhoneOrEmail: "",

      adjustButtonDisabled: true,
      depToTreeButtonDisabled: true,
      empDepRelationVisible: false,
      depTreePopoverVisible: false,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true
      },
      // columns,
      // 待分配员工信息
      empData: {},
      // 员工调整后部门
      empToDep: "",

      position: [],
      perPosition: {},
      positionForm: this.$form.createForm(this),
      positionTypeDialog: {},

      positionDialog: {},
      positionRules: {
        name: { required: true, message: "不可为空" },
        code: { required: true, message: "不可为空" }
      }
    };
  },
  computed: {
    ...mapState(["hr"])
  },
  watch: {
    selectedId: {
      handler(newVal) {
        if (newVal) {
          this.initData(this.selectedId);
        }
      },
      immediate: true
    }
  },
  created() {},
  methods: {
    Province() {
      getProvince().then((res) => {
        this.province = this.tree(res.data, "children", true);
      });
    },
    selectProvince(id, adr) {
      // this.addressId1 = id
      this.address = adr;
      this.changValue = true;
    },
    tree(array, childKey, onlyLastChild) {
      if (array === null || array.length < 1) {
        return [];
      }
      array.map((item, index) => {
        item["value"] = item.id + "";
        item["key"] = item.id;
        item["label"] = item.name;
        item["children"] = item[childKey];

        if (item.children) {
          item["disabled"] = onlyLastChild;
          this.tree(item.children, childKey, onlyLastChild);
        }
      });
      return array;
    },
    initData(id, depName) {
      getDepManageByDepId({
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        companyId: this.hr.companyId,
        depName,
        depId: id
      }).then((res) => {
        this.data = res.data.entities;
        this.pagination.total = res.data.entityCount || 0;
      });
    },
    tableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.initData(this.selectedId, this.searchDetail);
    },
    showDrawer() {
      this.title = "添加部门";
      this.visible = true;

      // 请求所有负责人
      this.allEmp();
      this.form.resetFields();

      setTimeout(() => {
        this.form.setFieldsValue({
          virural: false
        });
      }, 0);
    },
    onClose() {
      this.visible = false;
    },
    allEmp() {
      listAll({ companyId: this.hr.companyId }).then((res) => {
        this.allEmpInfo = res.data;
      });
    },
    handleSubmit(e) {
      var that = this;
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.title === "添加部门") {
            const info = {
              level: this.level,
              parentId: this.selectedId,
              address: this.address ? this.address[0] : ""
            };
            addDepartment({
              ...values,
              ...info,
              sort: 1,
              companyId: this.hr.companyId
            }).then((res) => {
              that.$notification["success"]({
                message: "success",
                description: "部门添加成功"
              });
              this.$store.dispatch("company/loadDepartmentsAct", this.hr.companyId);
              that.visible = false;
              that.initData(this.selectedId);
              this.$emit("updateDep", res.data.id, res.data.parentId);
            });
          } else {
            values.companyId = this.hr.companyId;
            values.sort = 1;
            values.parentId = this.record.parentId;
            values.id = this.record.id;
            values.level = this.record.level;
            if (this.changValue) {
              values.address = this.address[0];
            }
            putDepartment(values).then((res) => {
              that.$notification["success"]({
                message: "success",
                description: "修改成功"
              });
              this.$store.dispatch("company/loadDepartmentsAct", this.hr.companyId);
              that.visible = false;
              that.initData(this.selectedId);
              this.$emit("updateDep", res.data.id, res.data.parentId);
            });
          }
        }
      });
    },
    del() {
      var that = this;
      this.$confirm({
        title: "删除部门",
        content: "此操作将删除部门, 是否继续?",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          delDepartments(that.selectedRowKeys).then((res) => {
            that.$notification.open({
              title: "Success",
              message: "部门删除成功",
              type: "success",
              duration: 1
            });
            that.initData(that.selectedId);
            that.selectedRowKeys = [];
            that.$emit("getTree");
          });
        },
        onCancel() {}
      });
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    treeFunc(array, childKey) {
      if (!array) {
        return [];
      }
      array.map((item, index) => {
        item["value"] = item.id;
        item["key"] = item.id;
        item["label"] = item.name;
        item["children"] = item[childKey];

        if (item.children) {
          this.treeFunc(item.children, childKey);
        }
      });
      return array;
    },
    edit(record) {
      this.title = "编辑部门";
      this.visible = true;
      this.record = record;

      this.changValue = false;

      this.form.resetFields();
      setTimeout(() => {
        this.form.setFieldsValue({
          name: record.name,
          desc: record.desc
        });
      }, 100);
    },
    onSearch(value) {
      this.pagination.current = 1;
      this.initData(this.selectedId, value);
    }
  }
};
</script>
